<?php

namespace mpend\models\searchs;

use Yii;

/**
 * 资讯模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ArticleSearch extends \common\models\cms\CmsArticle {

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->active(static::STATUS_ACTIVE);
        $query->innerJoinWith('channel channel');
        $query->andWhere([
            '!=', 'channel.scope', 'match'
        ]);
        if ($this->channel_id) {
            $query->andWhere([
                $alias . 'channel_id' => $this->channel_id,
            ]);
        }
        $query->orderBy([
            $alias . 'recommend_id' => SORT_DESC,
            $alias . 'publish_at' => SORT_DESC,
            $alias . 'updated_at' => SORT_ASC,
        ]);
        $query->debug();
        return $query;
    }

    public function getDefaultMedias() {
        $path = $this->thumbUrl;
        if (!$path) {
            return [];
        }
        return [
            [
                'path' => $path,
                'format' => 'image',
            ]
        ];
    }

    public function getGalleryMedias() {
        return $this->album;
    }

    public function getVideoMedias() {
        $path = $this->thumbUrl;
        $video = $this->video;
        if ($video->thumb) {
            $path = $video->thumb;
        }
        return [
            [
                'path' => $path,
                'format' => 'video',
            ]
        ];
    }

    public function getMedias() {
        if ($this->hasProperty($this->format . 'Medias')) {
            return $this->{$this->format . 'Medias'};
        }
        return [];
    }

    public function getLayout() {
        $format = $this->format;
        if ($format === 'gallery') {
            return 'fence';
        }
        return $format;
    }

    public function getExtras() {
        $views = null;
        if ($this->stats && $this->stats->views) {
            $views = $this->stats->views . '浏览';
        }
        $channelName = null;
        if ($this->channel) {
            $channelName = $this->channel->name;
        }
        $publishTime = $this->publishTime;
        if ($this->channel) {
            $channelName = $this->channel->name;
        }
        $data = array_filter([
            $channelName, $views, $publishTime
        ]);
        return implode(' ', $data);
    }

    /**
     * 接口返回基础数据结构
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'title',
            'description' => 'extras',
            'format' => 'layout',
            'medias',
            'mplink',
        ];
    }

}
